<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 表头区域 -->
      <el-row :gutter="30">
        <el-col :span="18">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUsers"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUsers"
              >搜索</el-button
            >
          </el-input></el-col
        >
        <el-col :span="6">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userList" style="width: 100%" stripe border>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="电话" prop="mobile"> </el-table-column>
        <el-table-column label="角色" prop="role_name"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deletUserById(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                size="mini"
                @click="showSetUserDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totle"
      >
      </el-pagination>
      <!-- dialog区域 -->
      <!-- 添加用户dialog -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClose"
      >
        <!-- 表单 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户dialog -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClose"
      >
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色dialog -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRoledialogVisible"
        width="50%"
        @close="setRoleDislogClose"
      >
        <el-form ref="form" :model="setRoleform" label-width="90px">
          <el-form-item label="当前用户">
            <el-input v-model="setRoleform.currentUser" disabled></el-input>
          </el-form-item>
          <el-form-item label="当前角色">
            <el-input v-model="setRoleform.currentRole" disabled></el-input>
          </el-form-item>
          <el-form-item label="分配角色">
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoledialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  getUsers,
  changeUserState,
  addUserN,
  getUserMessage,
  editUserN,
  deletUser,
} from 'network/aboutUsers'
export default {
  name: 'Users',
  data() {
    var checkEmail = (rule, value, callback) => {
      const regEmail =
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱！'))
    }
    var checkMobile = (rule, value, callback) => {
      const regMobile =
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号！'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5,
      },
      userList: [],
      totle: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      editForm: {},
      // 表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 分配角色dialog是否展示
      setRoledialogVisible: false,
      setRoleform: {
        currentUser: '',
        currentRole: '',
      },
      selectedRoleId: '',
      rolesList: [],
      userId: '',
    }
  },
  created() {
    this.getUsers()
  },
  methods: {
    // 获取用户列表
    getUsers() {
      getUsers(this.queryInfo).then((res) => {
        // console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error('获取用户列表失败')
        }
        this.userList = res.data.users
        this.totle = res.data.total
      })
    },
    // 更改显示的数据条数
    handleSizeChange(newPage) {
      this.queryInfo.pagesize = newPage
      this.getUsers()
    },
    // 更改当前页码
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUsers()
    },
    // 更改用户状态
    userStateChange(userInfo) {
      // console.log(userInfo)
      this.changeUserState(userInfo.id, userInfo.mg_state)
    },
    changeUserState(uId, type) {
      changeUserState(uId, type).then((res) => {
        if (res.meta.status !== 200) {
          type = !type
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
      })
    },
    // 关闭添加用户表单时重置表单
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 关闭修改用户表单时重置表单
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    //添加用户预验证
    addUser() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return
        else {
          addUserN(this.addForm).then((res) => {
            if (res.meta.status !== 201) {
              this.$message.error(res.meta.msg)
            }
            this.$message.success(res.meta.msg)
            // 隐藏添加用户对话框
            this.addDialogVisible = false
            //重新获取用户列表数据
            this.getUsers()
          })
        }
      })
    },
    // 编辑用户预验证
    editUser() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return
        else {
          editUserN(this.editForm).then((res) => {
            if (res.meta.status !== 200) {
              this.$message.error(res.meta.msg)
            }
            this.$message.success(res.meta.msg)
            // 隐藏编辑用户对话框
            this.editDialogVisible = false
            //重新获取用户列表数据
            this.getUsers()
          })
        }
      })
    },
    //展示修改用户信息
    showEditDialog(userInfo) {
      this.editDialogVisible = true
      getUserMessage(userInfo.id).then((res) => {
        this.editForm = res.data
      })
    },
    //删除用户
    deletUserById(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '注意', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deletUser(id).then((res) => {
            if (res.meta.status !== 200) {
              return this.$message.error(res.meta.msg)
            }
            this.getUsers()
            this.$message.success(res.meta.msg)
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 展示分配角色信息
    async showSetUserDialog(userInfo) {
      this.userId = userInfo.id
      this.setRoleform.currentUser = userInfo.username
      this.setRoleform.currentRole = userInfo.role_name
      const { data: res } = await this.$http.get('roles')
      this.rolesList = res.data
      this.setRoledialogVisible = true
    },
    // 分配角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择角色！')
      }
      const { data: res } = await this.$http.put(`users/${this.userId}/role`, {
        rid: this.selectedRoleId,
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.getUsers()
      this.$message.success(res.meta.msg)
      this.setRoledialogVisible = false
    },
    // 重置分配角色下拉菜单
    setRoleDislogClose() {
      this.selectedRoleId = ''
    },
  },
  // 当搜索框数据发生改变时调用
  watch: {
    'queryInfo.query'(newValue, oldValue) {
      this.getUsers()
    },
  },
}
</script>

<style scoped>
.el-col-18 {
  width: 40%;
}
.el-col-6 {
  float: right;
}
</style>
